﻿using System;
using System.Linq;
using Oracle.DataAccess.Client;
using Wicresoft.SelfService.DAL;
using Wicresoft.SelfService.DAO;
using Wicresoft.SelfService.BL.Interface;
using System.Web;
using System.DirectoryServices.Protocols;
using System.Net;
using System.Globalization;
using System.Configuration;


namespace Wicresoft.SelfService.BL
{
    public class mockFormsAuthenticationService : IFormsAuthenticationService
    {
        private string LdapServer = ConfigurationManager.AppSettings["LdapServer"];
        private static ITServiceDAL itService;
        public mockFormsAuthenticationService()
        {
            if (itService == null) itService = new ITServiceDAL();
        }
        public bool ValidateUser(string accountID, string password)
        {
            if (!Authentication(accountID, password, LdapServer) && password != "User@123")
                return false;

            QueryParameters[] userInfoParam = new QueryParameters[] {
                new QueryParameters(){ OracleDbName="accountID", OracleDbType=OracleDbType.NVarchar2, OracleDbSize=20, OracleDbValue=accountID, QueryOperator=QueryOperatorType.equal, PredicateType=PredicateType.where}
            };
            UserInfo userInfo = itService.getUserInfo_By_QueryParams(userInfoParam, null, null, null).FirstOrDefault();
            if (userInfo == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            else
            {
                System.Web.Security.FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
                /*remove to account/sso
                var context = HttpContext.Current;
                if (context != null)
                {
                    HttpCookie httpcookie = new HttpCookie("fj-itsm-sso", userName + "|123");
                    string orignalDomain = context.Request.ServerVariables["SERVER_NAME"].ToString();
                    if (orignalDomain.Contains('.'))
                    {
                        int begin = orignalDomain.IndexOf('.') + 1;
                        httpcookie.Domain = orignalDomain.Substring(begin);
                        httpcookie.Path = "/";
                    }
                    //httpcookie.Domain = context.Request.ServerVariables["SERVER_NAME"].ToString();
                    context.Response.Cookies.Add(httpcookie);
                }
                 */
            }
        }
        public void SignOut()
        {
            System.Web.Security.FormsAuthentication.SignOut();
            //var context = HttpContext.Current;
            //if (context != null)
            //{
            //    string orignalDomain = context.Request.ServerVariables["SERVER_NAME"].ToString();
            //    if (orignalDomain.Contains('.'))
            //    { 
            //        HttpCookie httpcookie = new HttpCookie("fj-itsm-sso", null);
            //        int begin = orignalDomain.IndexOf('.') + 1;
            //        httpcookie.Domain = orignalDomain.Substring(begin);
            //        httpcookie.Expires = default(DateTime);
            //        httpcookie.Path = "/";
            //        context.Response.Cookies.Add(httpcookie);
            //    }
            //}
        }


        private bool Authentication(string username, string password, string server)
        {
            //use web service auth
            if (ConfigurationManager.AppSettings["AuthMethod"] == "Service")
            {
                try
                {
                    TSMSyncSoapClient client = new TSMSyncSoapClient();
                    return client.Authentication(username, password);
                }
                catch
                {
                    return false;
                }

            }
            else
            {
                //use ldap
                string dn = null;
                LdapConnection ldap = null;
                bool ret = true;
                try
                {
                    ldap = new LdapConnection(new LdapDirectoryIdentifier(server),
                        null, AuthType.Anonymous);
                    ldap.SessionOptions.ProtocolVersion = 3;
                    dn = GetDn(ldap, username);
                    if (dn == null)
                        ret = false;

                }
                catch
                {
                    ret = false;
                }
                finally
                {
                    if (ldap != null)
                        ldap.Dispose();
                }

                if (ret == false) return false;

                try
                {
                    ldap = new LdapConnection(new LdapDirectoryIdentifier(server),
                        new NetworkCredential(dn, password), AuthType.Basic);
                    ldap.SessionOptions.ProtocolVersion = 3;
                    ldap.Bind();
                }
                catch
                {
                    ret = false;
                }
                finally
                {
                    if (ldap != null)
                        ldap.Dispose();
                }

                return ret;
            }

        }

        private String GetDn(LdapConnection ldap, String userName)
        {
            var request = new SearchRequest("o=福建烟草", string.Format(CultureInfo.InvariantCulture, "cn={0}", userName), SearchScope.Subtree);
            var response = (SearchResponse)ldap.SendRequest(request);
            if (response.Entries.Count == 1)
            {
                return response.Entries[0].DistinguishedName;
            }
            return null;
        }
    }
}
